package com.knowif.backend.controller;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import com.knowif.aliOSS.enumConfig.AliOSSConfig;
import com.knowif.aliOSS.service.AliyunFileUtil;
import com.knowif.backend.config.WxMaConfiguration;
import com.knowif.system.model.RestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

/**
 * @author ：Xh
 * @date ：Created in 2019/6/20 0020 21:15
 */
@RestController
@RequestMapping("/wechat")
public class WechatQrCodeController {

    @Autowired
    private WxMaConfiguration wxMaConfiguration;
    @Autowired
    AliyunFileUtil aliyunFileUtil;
    @Value("${OSS.config.file.defaultPath}")
    private String defaultImage;

    @GetMapping("/qrCode")
    public RestBean qrCode(@RequestParam("teacherId") int teacherId) {
        WxMaQrcodeService qrcodeService = wxMaConfiguration.service().getQrcodeService();
        try {
            String teacherParam = teacherId + "";
            File wxaCodeUnlimit = qrcodeService.createWxaCodeUnlimit(teacherParam, "myPages/teacher/teacher");
            FileInputStream fis = new FileInputStream(wxaCodeUnlimit);
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
            String fileName = uuid;
            String suffix = "." + wxaCodeUnlimit.getPath().substring(wxaCodeUnlimit.getPath().lastIndexOf(".") + 1);
            fileName = (fileName + suffix).toUpperCase();
            aliyunFileUtil.fileUpload(AliOSSConfig.ALIIMAGE_STUDENT.setFileName(fileName), fis);
            return RestBean.buildSuccess(defaultImage + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return RestBean.buildError("系统异常");
        }
    }
}
